import { asyncRoutes, constantRoutes } from '@/router'
import { getRouters } from '@/api/user'
/* Layout */
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
  // myRoutes:[]
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
  // SET_MY_ROUTES:(state,routes)=>{
  //   state.myRoutes = routes
  // }
}

var myRouters;

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      console.log("role[0]为:",roles[0])
      console.log("roles为:",roles)
      
      // let myRouters = []
      //getRouters方法
      getRouters(roles[0]).then(res =>{
        // 向后端请求路由数据
        myRouters = myFilterAsyncRouter(res.data.routers)
        myRouters.push({path: '*', redirect: '/404', hidden: true})

        // commit("SET_MY_ROUTES",myRouters)
        // resolve(myRouters)
        console.log("后台传过来的路由1:",myRouters)
        
        console.log("后台传过来的路由2:",myRouters)
        let accessedRoutes

        //如果roles这个数组包含“admin"
        if (roles.includes('2')) {
          accessedRoutes = asyncRoutes || []
        } else {
          // 如果不是管理员⻆⾊，那么根据对应的⻆⾊过滤权限
          // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
          accessedRoutes = filterAsyncRoutes(myRouters, roles)
        }

        console.log("从router/index.js读到的路由accessedRoutes",accessedRoutes)

        // commit('SET_ROUTES', accessedRoutes)
        commit('SET_ROUTES', myRouters)

        // resolve(accessedRoutes)
        resolve(myRouters)
        console.log("后台传过来的路由3:",myRouters)
      })
    })
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function myFilterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
	// 如果有子路由，则采用递归的方式
    if (route.children != null && route.children && route.children.length) {
      route.children = myFilterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) =>  require([`@/views/${view}`], resolve)
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
